package com.malou.server.base.util;

import java.util.List;

import com.extjs.gxt.ui.client.data.FilterConfig;
import com.extjs.gxt.ui.client.data.FilterPagingLoadConfig;

public class GxtGridPaginate{
	public Integer offset; 
	public Integer limit;	
	public String order = "";
	public Integer tienda_id = null;
	public Integer maestro_id = null;
	public FilterPagingLoadConfig config;
	
	public String searchField;
    public String searchString;
    public String searchOper;
    public String searchType;
    
    public String condition =  "";
	
	public GxtGridPaginate(){
		
	}
	
	public void setLimit(){
		
		this.limit = config.getLimit();
		this.offset = config.getOffset();
		if(config.getSortField() != null){			
			this.order = "order by "+config.getSortField()+" "+config.getSortDir();			
		}
		
		List<FilterConfig> filters = config.getFilterConfigs();
		if(filters != null)
		for (FilterConfig f : filters) {
			
			this.searchString = f.getValue().toString();
			if(f.getComparison() != null)
				this.searchOper = this.getOper(f.getComparison());
		    this.searchField = f.getField();
		    this.searchType = f.getType();
		    this.setCondition();
		    //comparison c =>
		    //null representa String
		    //lt representa <
		    //gt representa >
		    //eq representa =
		    
		    //numeric or string		    
		    //System.out.println(f.getType());
		    
		}
	}
	
	private void setCondition(){
		String wh = "";       
        
	    wh += " and "+this.searchField+" ";
	    if(this.searchType.equals("numeric")){
	    	wh += this.searchOper+" "+this.searchString;
	    }else if(this.searchType.equals("string")){
	    	wh += " ilike '%"+this.searchString+"%'";
	    }else if(this.searchType.equals("date")){
	    	wh += this.searchOper+" '"+this.searchString+"'";
	    }
	    
	    this.condition += wh;
        
   }
	private String getOper(String oper){
		
		String retorno = "";
		
		if(oper.equals("lt"))
			retorno = " < ";
		else if(oper.equals("gt"))
			retorno = " > ";
		else if(oper.equals("eq"))
			retorno = " = ";
		else if(oper.equals("on"))
			retorno = " = ";
		else if(oper.equals("before"))
			retorno = " <= ";
		else if(oper.equals("after"))
			retorno = " >= ";
		return retorno;
	}
	
}
